// 阅读助手功能
class ReadAloud {
    constructor() {
        this.speechSynthesis = window.speechSynthesis;
        this.isReading = false;
        this.init();
        console.log('ReadAloud initialized'); // Added log
    }

    init() {
        // 创建阅读助手按钮
        const btn = document.createElement('div');
        btn.id = 'readAloudBtn';
        btn.className = 'read-aloud-btn';
        btn.title = '点击朗读内容';
        btn.innerHTML = '<i class="fa fa-volume-up"></i>';
        document.body.appendChild(btn);

        // 添加事件监听
        btn.addEventListener('click', () => this.toggleReadAloud());
        console.log('ReadAloud button added and event listener attached'); // Added log
    }

    toggleReadAloud() {
        console.log('toggleReadAloud called'); // Added log
        const btn = document.getElementById('readAloudBtn');
        const icon = btn.querySelector('i');

        if (this.isReading) {
            console.log('Stopping speech'); // Added log
            this.speechSynthesis.cancel();
            this.isReading = false;
            btn.classList.remove('active');
            icon.className = 'fa fa-volume-up';
        } else {
            console.log('Attempting to start speech'); // Added log
            // 获取当前可见内容
            const visibleContent = this.getVisibleContent();
            console.log('Visible content found:', visibleContent); // Added log

            if (visibleContent) {
                const utterance = new SpeechSynthesisUtterance(visibleContent);
                utterance.lang = 'zh-CN';
                utterance.rate = 1.0;
                utterance.pitch = 1.0;
                utterance.volume = 1.0;

                utterance.onerror = (event) => {
                    console.error('朗读出错:', event);
                    this.isReading = false;
                    btn.classList.remove('active');
                    icon.className = 'fa fa-volume-up';
                };

                utterance.onend = () => {
                    console.log('Speech ended'); // Added log
                    this.isReading = false;
                    btn.classList.remove('active');
                    icon.className = 'fa fa-volume-up';
                };

                if (this.speechSynthesis.speaking) {
                    this.speechSynthesis.cancel();
                }

                console.log('Calling speechSynthesis.speak()'); // Added log
                this.speechSynthesis.speak(utterance);
                this.isReading = true;
                btn.classList.add('active');
                icon.className = 'fa fa-stop';
            } else {
                console.warn('No visible content to read.'); // Added log
            }
        }
    }

    getVisibleContent() {
        console.log('getVisibleContent called'); // Added log
        // 获取当前页面的主要内容
        let mainContent;

        // 根据当前页面选择不同的内容区域
        const currentPage = window.location.pathname.split('/').pop() || 'index.html'; // Added default
        console.log('Current page:', currentPage); // Added log

        if (currentPage.endsWith('index.html') || currentPage === '/') {
            // 首页特殊处理
            mainContent = document.querySelector('main');
            console.log('Selected main content for index page:', mainContent); // Added log
        } else {
            // Other pages
            // Using a broader selector that should include the main content area on most pages
            mainContent = document.querySelector('main, .container'); // Simplified selector
            console.log('Selected main content for other page:', mainContent); // Added log
        }

        if (!mainContent) {
            console.warn('Main content element not found with selector.', document.querySelector('main, .container')); // Added log
            return null;
        }

        // 获取所有文本内容
        let content = '';
        // Expanded selectors to include more potential text containers like list items and specific content classes
        const elements = mainContent.querySelectorAll('h1, h2, h3, h4, h5, h6, p, span, div, li, article, section, .service-card, .card-body, .text-neutral-dark, .text-gray-600'); // Expanded selectors
        console.log('Found potential text elements (' + elements.length + '):', elements); // Added log

        const viewportHeight = window.innerHeight; // Defined viewportHeight here

        elements.forEach(element => {
            // 检查元素是否在视口中可见
            const rect = element.getBoundingClientRect();
            const style = window.getComputedStyle(element);
            const isVisible = (
                rect.top >= 0 &&
                rect.left >= 0 &&
                rect.bottom <= viewportHeight && // Use defined viewportHeight
                rect.right <= window.innerWidth &&
                style.display !== 'none' &&
                style.visibility !== 'hidden' &&
                style.opacity !== '0' &&
                element.offsetParent !== null
            );

            if (isVisible) {
                const text = element.innerText.trim();
                if (text && !element.closest('.read-aloud-btn')) {
                    // 根据元素类型添加不同的前缀
                    let prefix = '';
                    // Simplified prefix logic, focusing on common structural elements
                    if (element.tagName.toLowerCase().startsWith('h')) {
                        prefix = '标题：';
                    } else if (element.tagName.toLowerCase() === 'li') {
                         prefix = '点：';
                    } else if (element.classList.contains('list-title')) { // Still include specific classes if they are important
                        prefix = '分类：';
                    } // Removed item-title/desc prefixes for simplicity, can add back if needed

                    // Basic check to avoid reading very short or non-meaningful text blocks
                    if (text.length > 5 || prefix !== '') { // Only add non-empty text or text with a structural prefix
                         content += prefix + text + '\n';
                    }
                }
            }
        });

        console.log('Collected visible content:', content.trim()); // Added log
        return content.trim();
    }
}

// 当页面加载完成后初始化阅读助手
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOMContentLoaded fired'); // Added log
    if ('speechSynthesis' in window) {
        console.log('SpeechSynthesis supported.'); // Added log
        new ReadAloud();
    } else {
        console.error('您的浏览器不支持语音合成功能');
    }
});